package com.by.redis.utility.lock;

import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Slf4j
@Configuration
@EnableAutoConfiguration
@ConditionalOnProperty(name = "by.redis.lock.enabled", havingValue = "true")
@EnableConfigurationProperties(ByLockRedisProperties.class)
public class ByLockRedisConfig {

    @Resource
    private ByLockRedisProperties byLockRedisProperties;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        log.info("[ByLockRedisConfig][redissonClient] byLockRedisProperties:[{}]", byLockRedisProperties);
        config.useSingleServer()
                .setAddress("redis://" + byLockRedisProperties.getHost() + ":" + byLockRedisProperties.getPort())
                .setPassword(byLockRedisProperties.getPassword())
                .setDatabase(byLockRedisProperties.getDatabase())
                .setConnectionMinimumIdleSize(10)
                .setConnectionPoolSize(15)
                .setKeepAlive(true)
                .setDnsMonitoringInterval(1000);
        config.setCodec(new JsonJacksonCodec());
        RedissonClient redissonClient = Redisson.create(config);
        log.info("[ByLockRedisConfig][redissonClient] 配置信息为:{}", JSON.toJSONString(byLockRedisProperties));
        return redissonClient;
    }

}
